package com.coai.user.controller

import com.coai.common.dto.ApiResponse
import com.coai.user.model.OrgType
import com.coai.user.service.OrganizationInfo
import com.coai.user.service.OrganizationNode
import com.coai.user.service.OrganizationService
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/organizations")
class OrganizationController(
    private val organizationService: OrganizationService
) {
    
    /**
     * 创建组织
     */
    @PostMapping
    fun createOrganization(
        @RequestBody request: CreateOrganizationRequest,
        @AuthenticationPrincipal userId: String
    ): ApiResponse<Any> {
        val org = organizationService.createOrganization(
            name = request.name,
            code = request.code,
            parentId = request.parentId,
            type = request.type,
            leaderId = request.leaderId
        )
        return ApiResponse.success(org, "组织创建成功")
    }
    
    /**
     * 获取组织树
     */
    @GetMapping("/tree")
    fun getOrganizationTree(
        @RequestParam(required = false) parentId: String?
    ): ApiResponse<List<OrganizationNode>> {
        val tree = organizationService.getOrganizationTree(parentId)
        return ApiResponse.success(tree)
    }
    
    /**
     * 添加用户到组织
     */
    @PostMapping("/members")
    fun addMember(
        @RequestBody request: AddMemberRequest,
        @AuthenticationPrincipal userId: String
    ): ApiResponse<Unit> {
        organizationService.addUserToOrganization(
            userId = request.userId,
            organizationId = request.organizationId,
            isPrimary = request.isPrimary,
            position = request.position
        )
        return ApiResponse.success(message = "成员添加成功")
    }
    
    /**
     * 获取用户的组织
     */
    @GetMapping("/user/{userId}")
    fun getUserOrganizations(
        @PathVariable userId: String
    ): ApiResponse<List<OrganizationInfo>> {
        val orgs = organizationService.getUserOrganizations(userId)
        return ApiResponse.success(orgs)
    }
    
    /**
     * 获取组织成员
     */
    @GetMapping("/{organizationId}/members")
    fun getOrganizationMembers(
        @PathVariable organizationId: String
    ): ApiResponse<List<String>> {
        val members = organizationService.getOrganizationMembers(organizationId)
        return ApiResponse.success(members)
    }
}

data class CreateOrganizationRequest(
    val name: String,
    val code: String,
    val parentId: String?,
    val type: OrgType,
    val leaderId: String?
)

data class AddMemberRequest(
    val userId: String,
    val organizationId: String,
    val isPrimary: Boolean = false,
    val position: String?
)
